package com.ygqh.baby.controller.mobile;

import java.math.BigDecimal;
import java.util.*;

import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.model.CardCouponAction;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.impl.DocumentConstant;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.ygqh.baby.model.CardCouponOrderInfo;
import com.ygqh.baby.model.YgCardCouponInfo;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.SessionUtil;

@Controller()
@RequestMapping("/mobile/cardCoupon")
public class YgCardCouponController extends BaseController {
	protected Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	private YgCardCouponService ygCardCouponService;
	@Autowired
	private YgCardCouponDetailService ygCardCouponDetailService;
	@Autowired
	private YgUserMemberService ygUserMemberService;
	@Autowired
	private RedisDao redisDao;
	@Autowired
	private YgReturnOrderService ygReturnOrderService;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private YgFrameCodeService ygFrameCodeService;
	@Autowired
	private DocumentConstant documentConstant;

	private final String cardCouponOrderInfoPrefix = "card_coupon_order_info:";

	/**
	 * 个人中心展示
	 *
	 * @param callback
	 * @return JSONPObject 返回类型
	 * @throws @date 2017年11月13日 下午5:37:56
	 * @Title: findByUserId
	 * @author （guohao）
	 * @version V1.0
	 */
	@RequestMapping(value = "/findByUserId")
	@ResponseBody
	public JSONPObject findByUserId(String callback, UseStatus useStatus, BigDecimal expressPrice) {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgCardCouponInfo> list = ygCardCouponDetailService.findCardInfoByUserId(user.getId(), useStatus);
		this.validateInCheckOrder(list, useStatus, expressPrice, user.getId());
		return new JSONPObject(callback, Message.success(list));
	}

	private void validateInCheckOrder(List<YgCardCouponInfo> list, UseStatus useStatus, BigDecimal expressPrice, Long userId) {
		Iterator<YgCardCouponInfo> iterator = list.iterator();
		boolean hasCard = false; // 是否已有运费卡
		Boolean oldVip = ygUserService.isVip(userId);
		while (iterator.hasNext()) {
			YgCardCouponInfo next = iterator.next();
			if (CardType.OrderGift.equals(next.getCardType())) {
				next.setTitle(next.getProductName());
			}
			if (UseStatus.UnUsed.equals(next.getUseStatus()) && DateConvertUtils.getDateStart(new Date()).after(next.getEndDate())) { // 未使用 且已过期的卡券
				next.setUseStatus(UseStatus.InValid);
			}
			if (useStatus != null && useStatus.equals(UseStatus.UnUsed)) { // 结算页
				if (UseStatus.InValid.equals(next.getUseStatus()) || next.getCardType().equals(CardType.OrderGift)) {
					iterator.remove();
				} else if (next.getCardMode().equals(CardMode.Card)) { // 运费卡
					if (oldVip || hasCard || (expressPrice != null && expressPrice.compareTo(BigDecimal.ZERO) == 0)) {
						iterator.remove();
					} else {
						hasCard = true;
					}
				} else if (CardType.PullNew.equals(next.getCardType()) && next.getPrice().compareTo(BigDecimal.ZERO) > 0) { // 需要付费购买的拉新活动卡券
					iterator.remove();
				}
			}
		}
		list.sort(Comparator.comparing(YgCardCouponInfo::getUseStatus));
	}

	@RequestMapping(value = "/findCardInfoById")
	@ResponseBody
	public JSONPObject findCardInfoByDetailId(Long cardDetailId, String callback) {
		YgCardCouponInfo list = ygCardCouponDetailService.findCardInfoByDetailId(cardDetailId);
		return new JSONPObject(callback, Message.success(list));
	}

	/**
	 * 兑换卡券
	 *
	 * @param cardDetailId
	 * @param addrInfo
	 * @param callback     入参
	 * @return JSONPObject 返回类型
	 * @throws @date 2017年11月14日 上午11:44:54
	 * @Title: cashGift
	 * @author （guohao）
	 * @version V1.0
	 */
	@RequestMapping(value = "/cashCard")
	@ResponseBody
	public JSONPObject cashCard(@RequestParam(required = true) Long[] cardDetailId, @RequestParam(required = true) String addrInfo, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		YgUserAddress address = JSON.parseObject(addrInfo, new TypeReference<YgUserAddress>() {
		});
		Message cashCard = null;
		for (Long detailId : cardDetailId) {
			cashCard = ygCardCouponDetailService.cashCard(detailId, user.getId(), address);
		}

		return new JSONPObject(callback, cashCard);
	}

	/**
	 * 获取某月卡券
	 *
	 * @param cardType
	 * @param date
	 * @param callback
	 * @return JSONPObject 返回类型
	 * @throws @date 2017年11月15日 下午1:28:41
	 * @Title: getCardByMonth
	 * @author （guohao）
	 * @version V1.0
	 */
	@RequestMapping(value = "/getCardsByMonth")
	@ResponseBody
	public JSONPObject getCardByMonth(CardType cardType, Date date, String callback) {
		if (date == null) {
			date = new Date();
		}
		Map<String, Object> res = new HashMap<String, Object>();
		List<YgCardCoupon> list = ygCardCouponService.findCardsByMonth(cardType, null, date);
		Map<String, BigDecimal> map = ygUserMemberService.getMapVipPrice();
		res.putAll(map);
		res.put("cardList", list);
		return new JSONPObject(callback, Message.success(res));
	}

	/**
	 * 通过卡券Id为用户生成卡券
	 *
	 * @param cardId
	 * @param callback 入参
	 * @return JSONPObject 返回类型
	 * @throws @date 2017年11月15日 下午1:29:13
	 * @Title: generateCard
	 * @author （guohao）
	 * @version V1.0
	 */
	@RequestMapping(value = "/generateCard")
	@ResponseBody
	public JSONPObject generateCard(Long cardId, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		if (!ygUserMemberService.isVip(user.getId())) {
			return new JSONPObject(callback, Message.error("亲，您没有领取权限。", user.getLevel()));
		}
		Message message = ygCardCouponDetailService.generateCardCoupon(user.getId(), cardId, null, null);
		return new JSONPObject(callback, message);
	}

	/**
	 * 非购买方式成为会员
	 *
	 * @param cardIds
	 * @param birthday
	 * @param callback 入参
	 * @return JSONPObject 返回类型
	 * @throws @date 2017年11月15日 下午1:29:55
	 * @Title: becomeToMemberNotPay
	 * @author （guohao）
	 * @version V1.0
	 */
	@RequestMapping(value = "/becomeToMemberNotPay")
	@ResponseBody
	public JSONPObject becomeToMemberNotPay(String cardIds, Date birthday, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		String[] res = redisDao.get("ToMemberNotPay").split(",");
		List<String> asList = Arrays.asList(res);
		if (!asList.contains(user.getUserName())) {
			return new JSONPObject(callback, Message.error("亲，你没有赠送女王的资格。", user.getUserName()));
		}

		ygUserMemberService.becomeToMemberNotPay(cardIds, user, birthday);

		return new JSONPObject(callback, Message.success(null));
	}

	@RequestMapping(value = "/shareCard")
	@ResponseBody
	public JSONPObject shareCard(@RequestParam Long cardId, String formId, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		Message message = ygCardCouponDetailService.shareCard(cardId, user.getId(), formId);
		return new JSONPObject(callback, message);
	}

	@RequestMapping(value = "/receiveCard")
	@ResponseBody
	public JSONPObject receiveCard(@RequestParam Long cardId, Long sharer, String callback) {
		YgUser user = SessionUtil.getCurrentUser();
		if (sharer.equals(user.getId())) {
			return new JSONPObject(callback, Message.error("亲，不可领取自己分享的卡券", null));
		}
		Message message = ygCardCouponDetailService.receiveCard(cardId, sharer, user.getId());
		return new JSONPObject(callback, message);
	}

	/**
	 * 根据订单id生成卡券
	 *
	 * @param orderId
	 * @param count
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "generateCardWithOrderId")
	@ResponseBody
	public JSONPObject generateCardWithOrderId(@RequestParam(required = true) Long orderId, Long count, String callback) {
		if (count == null) {
			CardCouponOrderInfo couponOrderInfo = findCardCouponOrderInfoByRedis(orderId);
			if (couponOrderInfo != null) {
				count = couponOrderInfo.getCount();
			}
		}
		Message message = ygCardCouponDetailService.generateCardWithOrderId(orderId, count, null, SessionUtil.getCurrentUser().getId());
		if (message.getType().equals(Message.Type.success)) {
			redisDao.del((cardCouponOrderInfoPrefix + orderId.toString()).getBytes());
		}
		return new JSONPObject(callback, message);
	}

	/**
	 * 卡券更换sku
	 *
	 * @param cardId
	 * @param changeSkuInfo sku更换信息，例：[{"sourceSkuId":434512,"skuId":434513, "amount":1}]
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "changeCardCouponRelationOrder")
	@ResponseBody
	public JSONPObject changeCardCouponRelationOrder(@RequestParam Long cardId, @RequestParam String changeSkuInfo, String callback) {
		return new JSONPObject(callback, ygCardCouponDetailService.changeCardCouponRelationOrder(cardId, changeSkuInfo, SessionUtil.getCurrentUser().getId()));
	}

	/**
	 * 保存送红包设置信息
	 *
	 * @param info     例：{"orderId": 61032312323, "count": 2, "imagePath": "XXXXx", "message": "ZZXXZZa"}
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "storeCardCouponOrderInfo")
	@ResponseBody
	public JSONPObject storeCardCouponOrderInfo(@RequestParam String info, String callback) {
		if (StringUtils.isBlank(info)) {
			return new JSONPObject(callback, Message.error("卡券设置信息为空", null));
		}
		CardCouponOrderInfo couponOrderInfo = JSONObject.parseObject(info, CardCouponOrderInfo.class);
		redisDao.set(cardCouponOrderInfoPrefix + couponOrderInfo.getOrderId().toString(), info, 24 * 60 * 60 * 1000);
		return new JSONPObject(callback, Message.success(1));
	}

	/**
	 * 获取指定订单，送红包设置信息
	 *
	 * @param orderId
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findCardCouponOrderInfo")
	@ResponseBody
	public JSONPObject findCardCouponOrderInfo(@RequestParam Long orderId, String callback) {
		return new JSONPObject(callback, Message.success(findCardCouponOrderInfoByRedis(orderId)));
	}

	private CardCouponOrderInfo findCardCouponOrderInfoByRedis(Long orderId) {
		String info = redisDao.get(cardCouponOrderInfoPrefix + orderId.toString());
		if (StringUtils.isBlank(info)) {
			return null;
		}
		return JSONObject.parseObject(info, CardCouponOrderInfo.class);
	}

	/**
	 * 获取卡券订单可更换的退单信息
	 *
	 * @param orderId
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findChangeOrderInfoByOrderId")
	@ResponseBody
	public JSONPObject findChangeOrderInfoByOrderId(@RequestParam Long orderId, String callback) {
		return new JSONPObject(callback, Message.success(ygReturnOrderService.findOrderInfo4Retrun(orderId, null, DataStatus.Delete)));
	}

	/**
	 * 获取指定卡券领取用户信息集
	 *
	 * @param cardDetailId
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findReceiverListByCardId")
	@ResponseBody
	public JSONPObject findReceiverListByCardId(@RequestParam Long cardDetailId, String callback) {
		return new JSONPObject(callback, Message.success(ygCardCouponDetailService.findReceiverListByCardId(cardDetailId)));
	}

	/**
	 * 拉新活动领取卡券
	 *
	 * @param sourceCode 分享链接来源
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "receiveCardCouponByPullNewAction")
	@ResponseBody
	public JSONPObject receiveCardCouponByPullNewAction(String sourceCode, String callback) {
		Message validatePullNewCardCoupon = ygCardCouponService.validatePullNewCardCoupon();
		if (!Message.isSuccess(validatePullNewCardCoupon)) {
			return new JSONPObject(callback, validatePullNewCardCoupon);
		}
		YgCardCoupon ygCardCoupon = (YgCardCoupon) validatePullNewCardCoupon.getExtra();
		YgUser currentUser = SessionUtil.getCurrentUser();
		if (currentUser.getSourceCode().equals(sourceCode)) {
			return new JSONPObject(callback, Message.error("亲，不能领取自己的分享", null));
		}
		if (!ygUserService.isNewCustom(currentUser.getId())) {
			return new JSONPObject(callback, Message.error("亲，只有新用户可以领取", null));
		}
		List<YgCardCouponInfo> list = ygCardCouponDetailService.findByCardIdAndUserId(ygCardCoupon.getId(), currentUser.getId());
		if (CollectionUtils.isNotEmpty(list)) {
			return new JSONPObject(callback, Message.error("亲，您已领取，请前往我的卡券查看。", null));
		}
		return new JSONPObject(callback, ygCardCouponDetailService.generateCardCoupon(currentUser.getId(), ygCardCoupon, null, null, sourceCode));
	}

	/**
	 * 拉新活动已领取好友
	 *
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findReceivedUserByPullNewAction")
	@ResponseBody
	public JSONPObject findReceivedUserByPullNewAction(String callback) {
		List<YgCardCoupon> cardsByMonth = ygCardCouponService.findCardsByMonth(CardType.PullNew, CardMode.Goods, null);
		if (CollectionUtils.isEmpty(cardsByMonth)) {
			return new JSONPObject(callback, Message.success(null));
		}
		YgCardCoupon ygCardCoupon = cardsByMonth.get(0);
		YgUser currentUser = SessionUtil.getCurrentUser();
		List<YgUser> userList = ygCardCouponDetailService.findReceiveUserListBySource(ygCardCoupon.getId(), currentUser.getSourceCode());
		return new JSONPObject(callback, Message.success(userList));
	}

	@RequestMapping(value = "findExpressPriceAndOrderId")
	@ResponseBody
	public JSONPObject findExpressPriceAndOrderId(String callback) {
		BigDecimal expressPrice = ygOrderService.getExpressPrice(BigDecimal.ZERO, SessionUtil.getCurrentUser().getId());
		Long orderId = ygFrameCodeService.getFrameCode(CodeType.RechargeMB, new Date());
		Map<String, Object> data = new HashMap<>();
		data.put("expressPrice", expressPrice);
		data.put("orderId", orderId);
		return new JSONPObject(callback, Message.success(data));
	}

	@RequestMapping(value = "cashCardByPayExpress")
	@ResponseBody
	public JSONPObject cashCardByPayExpress(@RequestParam Long cardDetailId, @RequestParam Long orderId, @RequestParam(defaultValue = "WeChat") AppType appType,
											@RequestParam(defaultValue = "WeChat") PayType payType, @RequestParam BigDecimal totalPrice, @RequestParam String addrInfo,
											String callback) {
		YgUserAddress address = JSON.parseObject(addrInfo, new TypeReference<YgUserAddress>() {
		});
		Message msg = ygCardCouponDetailService.cashCardByPayExpress(SessionUtil.getCurrentUser().getId(), cardDetailId, orderId, totalPrice, appType, payType, address);
		return new JSONPObject(callback, msg);
	}

	/**
	 * 领取卡券活动
	 *
	 * @param telPhone
	 * @param validateCode
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "receiveCardCouponAction")
	@ResponseBody
	public JSONPObject receiveCardCouponAction(@RequestParam String telPhone, @RequestParam String validateCode, String callback) {
		ValidateCode rightValidateCode = ygUserService.selectValidateCodeToRedis(telPhone);
		if (rightValidateCode == null || !rightValidateCode.getCode().equals(validateCode)) {
			return new JSONPObject(callback, Message.error(documentConstant.VALIDATE_CODE_NO_MATCHING, "VALIDATE_CODE_NO_MATCHING"));
		}
		CardCouponAction actionInfo = ygCardCouponService.getCardCouponActionInfoFromRedis();
		if (actionInfo == null) {
			return new JSONPObject(callback, Message.error("活动已结束", null));
		}
		Message validateActionDateMsg = actionInfo.validateActionDate();
		if (!Message.isSuccess(validateActionDateMsg)) {
			return new JSONPObject(callback, validateActionDateMsg);
		}
		Message message;
		YgUser user = ygUserService.findByUserName(telPhone);
		if (user == null) {
			message = Message.error("该手机号未注册壹果商城", null);
			message.setCode("1010");
		} else if (actionInfo.getOnlyNew() && !ygUserService.isNewCustom(user.getId())) {
			message = Message.success("新年快乐！本活动仅限新用户参与，感谢关注。", null);
		} else {
			message = ygCardCouponDetailService.receiveCardCouponAction(user.getId(), actionInfo);
		}
		return new JSONPObject(callback, message);
	}

}
